<template>
  <div class="recycle-bin">
    <div class="page-header">
      <h2>回收站</h2>
      <div class="header-actions">
        <el-button type="danger" @click="clearAll" :disabled="deletedUsers.length === 0" :loading="clearing">
          <i class="el-icon-delete"></i> 清空回收站
        </el-button>
        <el-button @click="fetchDeletedUsers" :loading="loading">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
    </div>

    <!-- 已删除用户表格 -->
    <el-table :data="deletedUsers" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="role" label="角色" width="100">
        <template slot-scope="scope">
          <el-tag :type="getRoleTag(scope.row.role)">{{ getRoleText(scope.row.role) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="删除时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button
              v-if="canRestore"
              size="mini"
              type="success"
              @click="handleRestore(scope.row)"
              :loading="scope.row.restoring">
            恢复
          </el-button>
          <el-button
              v-if="canPermanentDelete"
              size="mini"
              type="danger"
              @click="handlePermanentDelete(scope.row)"
              :loading="scope.row.deleting">
            彻底删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="!loading && deletedUsers.length === 0" class="empty-state">
      <i class="el-icon-delete" style="font-size: 64px; color: #ddd;"></i>
      <p>回收站为空</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RecycleBin',
  data() {
    return {
      deletedUsers: [],
      loading: false,
      clearing: false,
      currentUserRole: localStorage.getItem('userRole') || 'USER',
      currentUserId: localStorage.getItem('userId')
    }
  },
  computed: {
    // 是否可以恢复用户
    canRestore() {
      return this.currentUserRole === 'SUPER_ADMIN' || this.currentUserRole === 'ADMIN'
    },
    // 是否可以彻底删除用户
    canPermanentDelete() {
      return this.currentUserRole === 'SUPER_ADMIN' || this.currentUserRole === 'ADMIN'
    }
  },
  created() {
    this.fetchDeletedUsers()
  },
  methods: {
    // 获取已删除用户列表
    fetchDeletedUsers() {
      this.loading = true
      this.$axios.get('/api/users/deleted', {
        headers: {
          'X-Username': localStorage.getItem('username') || 'system'
        }
      })
          .then(response => {
            this.deletedUsers = response.data.map(user => ({
              ...user,
              restoring: false,
              deleting: false
            }))
          })
          .catch(error => {
            console.error('获取已删除用户失败:', error)
            this.$message.error('获取回收站数据失败')
          })
          .finally(() => {
            this.loading = false
          })
    },

    // 恢复用户
    handleRestore(user) {
      this.$confirm(`确认恢复用户 "${user.username}" 吗？`, '恢复确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        user.restoring = true
        const operatedBy = localStorage.getItem('username') || 'system'

        this.$axios.put(`/api/users/${user.id}/restore`, {}, {
          headers: {
            'X-Username': operatedBy
          }
        })
            .then(() => {
              this.$message.success('用户恢复成功')
              this.fetchDeletedUsers() // 刷新列表
            })
            .catch(error => {
              console.error('恢复用户失败:', error)
              if (error.response && error.response.status === 403) {
                this.$message.error('权限不足，无法恢复此用户')
              } else {
                this.$message.error('恢复用户失败')
              }
            })
            .finally(() => {
              user.restoring = false
            })
      }).catch(() => {})
    },

    // 彻底删除用户
    handlePermanentDelete(user) {
      this.$confirm(`确认彻底删除用户 "${user.username}" 吗？此操作不可恢复！`, '危险操作', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        user.deleting = true
        const operatedBy = localStorage.getItem('username') || 'system'

        this.$axios.delete(`/api/users/${user.id}/permanent`, {
          headers: {
            'X-Username': operatedBy
          }
        })
            .then(() => {
              this.$message.success('用户已彻底删除')
              this.fetchDeletedUsers() // 刷新列表
            })
            .catch(error => {
              console.error('彻底删除用户失败:', error)
              if (error.response && error.response.status === 403) {
                this.$message.error('权限不足，无法删除此用户')
              } else {
                this.$message.error('彻底删除用户失败')
              }
            })
            .finally(() => {
              user.deleting = false
            })
      }).catch(() => {})
    },

    // 清空回收站
    clearAll() {
      this.$confirm('确认清空整个回收站吗？此操作将彻底删除所有用户，不可恢复！', '危险操作', {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.clearing = true
        const operatedBy = localStorage.getItem('username') || 'system'

        this.$axios.delete('/api/users/recycle-bin/clear', {
          headers: {
            'X-Username': operatedBy
          }
        })
            .then(() => {
              this.$message.success('回收站已清空')
              this.fetchDeletedUsers() // 刷新列表
            })
            .catch(error => {
              console.error('清空回收站失败:', error)
              this.$message.error('清空回收站失败')
            })
            .finally(() => {
              this.clearing = false
            })
      }).catch(() => {})
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    // 获取角色标签类型
    getRoleTag(role) {
      switch (role) {
        case 'SUPER_ADMIN': return 'danger'
        case 'ADMIN': return 'warning'
        case 'USER': return 'info'
        default: return 'info'
      }
    },

    // 获取角色文本
    getRoleText(role) {
      switch (role) {
        case 'SUPER_ADMIN': return '超级管理员'
        case 'ADMIN': return '管理员'
        case 'USER': return '普通用户'
        default: return '未知'
      }
    }
  }
}
</script>

<style scoped>
.recycle-bin {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #999;
}

.empty-state p {
  margin-top: 16px;
  font-size: 16px;
}
</style>